# -*- coding: utf-8 -*-
__author__ = "Eduardo Lopes"
__copyright__ = "Copyright 2014, Planeta Terra"
__license__ = "Use por conta e risco - use by your own risc"
__version__ = "0.1-beta-bem-beta"
__status__ = "mais ou menos em Production"


import os
import sys
import shutil
import urllib2
import json

from xml.dom import minidom

def get_dependencies(project):
  xml = minidom.parse(project + "/" + ".classpath")
  items = xml.getElementsByTagName('classpathentry')
  deps = []
  for item in items:
      deps.append(item.attributes["path"].value)
  return deps    


def create_maven_dirs(projdir, webapp=False):
   os.makedirs(projdir + "/maven")
   os.makedirs(projdir + "/maven/src/main")
   os.makedirs(projdir + "/maven/src/main/java")
   os.makedirs(projdir + "/maven/src/resources")
   os.makedirs(projdir + "/maven/src/config")
   os.makedirs(projdir + "/maven/test/java")
   os.makedirs(projdir + "/maven/test/resources")
   if webapp:
    os.makedirs(projdir + "/maven/src/main/webapp")
    os.makedirs(projdir + "/maven/src/main/webapp/images")		
    os.makedirs(projdir + "/maven/src/main/webapp/templates")	
    os.makedirs(projdir + "/maven/src/main/webapp/css")


def create_text_node(document, nodename, value):
    node = document.createElement(nodename)
    text = document.createTextNode(value)
    node.appendChild(text)
    return node

def sanitize(name):
    #print name
    name = name.strip()
    if name.endswith(".jar"):
        n = name.strip().split("/")
        return str(n[-1:][0]).replace("/", "")
    else:
        return name.replace("/", "")


def query_maven_central(artifact, version, verbose=True):
   ''' retorns (groupId, artifact, version) from search.maven.org '''
   if verbose: print "Looking for maven artefact {0} version {1}".format(artifact, version),
   url = 'http://search.maven.org/solrsearch/select?q=a:%22{0}%22%20AND%20v:%22{1}%22&rows=1&wt=json'.format(artifact, version)

   try:
    data = urllib2.urlopen(url)
   except:
    return None

   response = json.load(data)
   response = response['response']
   if int(response['numFound']) > 0:
     if verbose: print "  [OK]"
     return (response['docs'][0]['g'], response['docs'][0]['a'], response['docs'][0]['v'])
   else:
     print u"\n\033[1;31m[ERROR]\033[1;m when querying search.maven.org for artifact {0}-{1} :-( ".format(artifact, version)
     return None
   	   	


def create_pom(project_dir, project_name, packaging, deps=[]):
    pom = minidom.Document()
    project = pom.createElement("project")
    project.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
    project.setAttribute("xmlns","http://maven.apache.org/POM/4.0.0")
    project.setAttribute("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd")

    pom.appendChild(project)

    model = create_text_node(pom, "modelVersion", "4.0.0")
    groupId = create_text_node(pom, "groupId", "br.gov.infoseg.{0}".format(project_name.strip().lower()))
    artifactId = create_text_node(pom, "artifactId", project_name.strip())
    version = create_text_node(pom, "version", "1.0")
    pack = create_text_node(pom, "packaging", packaging)
    name = create_text_node(pom, "name", project_name.strip())
    description = create_text_node(pom, "description", "")

    project.appendChild(model)
    project.appendChild(groupId)
    project.appendChild(artifactId)
    project.appendChild(version)
    project.appendChild(pack)
    project.appendChild(name)
    project.appendChild(description)

    if deps:
        dependencies = pom.createElement("dependencies")
        for d in deps:
            exclude = ['bin','src', 'src/java', 'src/test','WebRoot/WEB-INF/classes','src/main/java','src/main/config']
            exclude = exclude + ['src/test/config', 'src/test/java']
	    if d.startswith("org.eclipse.jst") or d.startswith('org.eclipse.jdt.launching'): continue
	    if d in exclude: continue	

            groupIdvalue = ""
	    versionvalue = ""	 
             
            artifactIdValue = sanitize(d)
            if artifactIdValue.endswith('.jar'):
		jar = artifactIdValue
		jar = jar.replace(".jar", "")
		nv = jar.split("-")
  	        v = nv[-1:]
		name = nv[0:-1]
		name = '-'.join(name)
 		artifactIdValue = name
  		versionvalue = str(v[0])
		t = query_maven_central(artifactIdValue, versionvalue)
		if t:
 		 groupIdvalue = t[0]
		 artifactIdValue = t[1]
		 versionvalue = t[2]			

            dep = pom.createElement("dependency")
            groupId = create_text_node(pom, "groupId", groupIdvalue)
            artifactId = create_text_node(pom, "artifactId", artifactIdValue)
	    version = create_text_node(pom, "version", versionvalue)	
            scope = create_text_node(pom, "scope", "compile")
            dep.appendChild(groupId)
            dep.appendChild(artifactId)
            dep.appendChild(version)
            dep.appendChild(scope)
            dependencies.appendChild(dep)

        project.appendChild(dependencies)

    build = pom.createElement("build")
    project.appendChild(build)

    plugins = pom.createElement("plugins")	
    build.appendChild(plugins)

    plugin = pom.createElement("plugin")
    plugins.appendChild(plugin)   
 
    plugingroupId = create_text_node(pom, "groupId", "org.apache.maven.plugins")
    plugin.appendChild(plugingroupId)

    pluginartifactid = create_text_node(pom, "artifactId", "maven-compiler-plugin")
    plugin.appendChild(pluginartifactid)

    pluginversion = create_text_node(pom, "version", "3.1")
    plugin.appendChild(pluginversion)
    
    pluginconfiguration = pom.createElement("configuration")
    plugin.appendChild(pluginconfiguration)

    pluginconfigationsource = create_text_node(pom, "source", "1.5")
    pluginconfigationtarget = create_text_node(pom, "target", "1.5")
    
    pluginconfiguration.appendChild(pluginconfigationsource)
    pluginconfiguration.appendChild(pluginconfigationtarget)

    filexml = open(project_dir + "/maven/pom.xml", "wb")
    xmlcontent = pom.toprettyxml()
    import re
    text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)    
    pretty_xml = text_re.sub('>\g<1></', xmlcontent)
    filexml.write(pretty_xml)
    filexml.close()




def is_maven(projectdir):
 for root,folders,files in os.walk(projectdir):
  for file in files:
   if file.endswith("pom.xml"):
    return True
 return False

def is_webapp(projectdir):
 for root,folders,files in os.walk(projectdir):
  for folder in folders:
   if folder.endswith("WEB-INF") or folder.endswith("WebRoot") or folder.endswith("WebContent"):
    return True
 return False


rootdir = sys.argv[1]



def copy_src_dir(project_path):
  scrdir = project_path + "/src" 	
  if os.path.exists(scrdir):
    files_and_dirs = os.listdir(scrdir)
    #retira os arquivos ficando somente os diretorios
    folders = list(filter((lambda f: os.path.isdir(scrdir+"/"+f)), files_and_dirs))
    if 'maven' in folders: folders.remove("maven")
    if '.svn' in folders: folders.remove(".svn")
    if 'lib' in folders: folders.remove("lib")

    for folder in folders: 
      src = scrdir +"/"+ folder
      dst = project_path + "/maven/src"
      if folder == "META-INF":
        dst = dst + "/resources/" + folder
      else:
        dst = dst + "/main/java/" + folder
        
      print "copying {0} to {1}".format(src, dst)
      shutil.copytree(src, dst)	



def copy_resources_dir(project_path):
 resources_dir = [project_path + "/src/resources", project_path + "/resources"]
 for resources in resources_dir:
  if os.path.exists(resources) and os.path.isdir(resources):
     dircontent = os.listdir(resources)	     
     for f in dircontent:
       if f == ".svn": continue	
       src =  resources + "/" + f
       dst =  project_path + "/maven/src/resources/{0}".format(f)	

       if os.path.isdir(src):
	print "copying {0} to {1}".format(src, dst)
	shutil.copytree(src, dst)	
       else:
	print "copying {0} to {1}".format(src, dst)
	try:
          shutil.copy(src, dst)
        except:
          #se der erro vai na teimoisia mesmo	
 	  os.system("cp {0} {1}".format(src, dst))
    	

def copy_web_content(project_path):
 webcontent = [project_path + "/WebRoot", project_path + "/WebContent"]
 for webpath in webcontent:
   if os.path.exists(webpath):
     dircontent = os.listdir(webpath)	     
     for f in dircontent:
       if f == ".svn": continue	
       src =  webpath + "/" + f
       dst =  project_path + "/maven/src/main/webapp/{0}".format(f)	

       if os.path.isdir(src):
	print "copiando diretorio {0} para {1}".format(src, dst)
	shutil.copytree(src, dst)	
       else:
	print "copiando arquivo {0} para {1}".format(src, dst)
        shutil.copy(src, dst)		


def copy_test_dir(project_path):
 testdirs = [project_path + "/src/test", project_path + "/test"]
 for testdir in testdirs:
   if os.path.exists(testdir):
     dircontent = os.listdir(testdir)	     
     for f in dircontent:
       if f == ".svn": continue	
       src =  testdir + "/" + f
       dst =  project_path + "/maven/test/java/{0}".format(f)	

       if os.path.isdir(src):
	print "copying {0} to {1}".format(src, dst)
	shutil.copytree(src, dst)	
       else:
	print "copying {0} to {1}".format(src, dst)
        shutil.copy(src, dst)		



if len(sys.argv) > 1: 
  rootdir = sys.argv[1]
  subdirs = os.listdir(rootdir)
  projects = [d for d in subdirs if os.path.isdir(rootdir + "/" + d)]
  
  for project in projects:
    project_path = rootdir +  project
    #deleta antigo diretorio maven criado por este script (i hope)
    if os.path.exists(project_path+"/maven"):
      shutil.rmtree(project_path+"/maven")
    if is_maven(project_path):
      #nao precisa fazer nada	
      continue  
    elif is_webapp(project_path):
       print "--" * 60
       print "Mavenizing webapp", project	        
       create_maven_dirs(project_path, True)	
       copy_src_dir(project_path)
       copy_test_dir(project_path)
       copy_resources_dir(project_path)
       copy_web_content(project_path)  	
       print "Creatinng pom.xml for project", project
       create_pom(project_path, project, "war", get_dependencies(project_path)) 
       print "Finished!"
       print "--" * 60     
    else:
       print "Mavenizing ", project
       create_maven_dirs(project_path, False)
       copy_src_dir(project_path)
       copy_test_dir(project_path)
       copy_resources_dir(project_path)
       print "Creating pom.xml for project", project
       create_pom(project_path, project, "jar", get_dependencies(project_path))    
       print "Finished!"
       print "--" * 60     
else:
   print "mavenizer <directory containning the eclipse projects>"


